#coding:utf-8
"""
*   TG_Coder : Dzlua
*   Email    : 505544956@qq.com
*   Time     : 2017/09/16
"""

from database import DataBase
import os

class DelErr(DataBase):
    dbname = 'librarys'
    dst_path = '/disk2/coledata/colelib/it'
    def __init__(self, host, user, pwd, db):
        DataBase.__init__(self, host, user, pwd, db)
    def _select(self, conn, sql):
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        return result
    def _getCount(self, conn):
        sql = 'SELECT count(*) FROM %s;' % self.dbname
        result = self._select(conn, sql)

        count = 0
        for r in result:
            count = r[0]
            break
        return count
    def start(self, bid, eid):
        print('[DelErr] check done files : ...')
        dfiles = self.done_files(self.dst_path)
        print('[DelErr] check done files : done! count: %s' % len(dfiles))
        self.read(self.__on_read, [bid, eid, dfiles])
        print('[DelErr] done : done!')
    def done_files(self, dst_path):
        dfiles = []
        for (_root,_dirs,_files) in os.walk(dst_path):
            for _dir in _dirs:
                dfiles.append(_dir)
            break
        return dfiles
    def has_file(self, name, dfiles):
        for file in dfiles:
            if file == name:
                return True
        return False
    def check(self, id, name, dfiles):
        if not self.has_file(name, dfiles):
            self.del_id_name(id, name)
    def __on_read(self, conn, args):
        bid = args[0]
        eid = args[1]
        dfiles = args[2]

        count = self._getCount(conn)
        id = bid
        while id < count and id <= eid:
            print('------------------------------')
            print('[DelErr] id:%s/%d[%s,%s], num:%s' % (id, count, bid, eid, id-bid+1) )
            sql = "SELECT id,name FROM %s WHERE id=%s;" % (self.dbname, id)
            result = self._select(conn, sql)
            for r in result:
                self.check(r[0], r[1].encode('utf8'), dfiles)
                break
            id = id +1
    def del_id_name(self, id, name):
        print('[DelErr] delete : id:%s, name:%s' % (id, name) )
        return
        sql = "DELETE FROM %s WHERE id=%s;" % (self.dbname, id)
        self.execute(sql)
#--------------------#
delerr = DelErr('localhost', 'dzlua', 'dzlua', 'spider')
delerr.start(0, 10311)
